//
//  HSMessagesTableViewController.swift
//  HomeSchoolDemo
//
//  Created by rimi on 16/9/26.
//  Copyright © 2016年 黄华强. All rights reserved.
//

import UIKit
/*
 使用测量而不是猜测
 
 表格视图的性能优化（性能调优）
 1.所有的图片不要使用圆角模式
 2.劲量不要透明
 3.所有参数提前准备好
 4.视图尽量不要延时加载
 5.不要让系统压缩图片
 6.cell中尽量不要让视图的图层太复杂
 7.尽量不要让系统计算行高（缓存行高）
 */
class HSMessagesTableViewController: HSBasicTableViewController {

    //消息列表视图模型
    let messageListVM = HSMessageslistViewModel()
    
    var inputToolBarV: UIView!
    //文本输入框
    var inputTextF: UITextField!
    
    var currentCell = HSMessagesTableViewCell()
    
    var currentOffsetY: CGFloat = 0
    
    var isMove = false
    
    //记录键盘
    var isKeyboardShow = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.register(UINib(nibName: "HSMessagesTableViewCell", bundle: nil), forCellReuseIdentifier: "messagesCell")
        tableView.estimatedRowHeight = 220
        //tableView.rowHeight = UITableViewAutomaticDimension
        
        let rightBtn = UIBarButtonItem(imageName: "release_msg_nor", bgImageName: "release_msg_press", target: self, action: #selector(rightBtnClicked))
        navigationItem.rightBarButtonItem = rightBtn
        //添加刷新控件
        loadData()
        inputTextView()
        //注册监听键盘弹出的通知
        NotificationCenter.default.addObserver(self, selector: #selector(notificationWithKeyboard(notify:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }
    
    @objc fileprivate func rightBtnClicked() {
        let keyWindow = UIApplication.shared.keyWindow
        keyWindow?.endEditing(true)

        let releseVc = HSReleaseInfoController()
        releseVc.hidesBottomBarWhenPushed = true
        navigationController?.pushViewController(releseVc, animated: true)
    }
    
    override func loadData() {
        refreshC.beginRefreshing()
        let loType = isPull ? LoadType.pull : LoadType.drop
        
        messageListVM.requestMessage(loadType: loType) {  [weak self](err, isRefresh) in
            self?.refreshC.endRefreshing()
            self?.isPull = false
            
            if err != nil  {
                return
            }
            if isRefresh {
                self?.tableView.reloadData()
            }

        }
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

   
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
}

// MARK: - Table view data source

extension HSMessagesTableViewController {
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return messageListVM.messages.count
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if isKeyboardShow {
            inputTextF.resignFirstResponder()
        }
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "messagesCell", for: indexPath) as! HSMessagesTableViewCell
        cell.selectionStyle = .none
        let messageVm = messageListVM.messages[indexPath.row]
        cell.messageVM = messageVm
        cell.likeBtnCallback = {[weak self](clickCell) -> () in
            self?.likeBtnClicked(cell: clickCell as! HSMessagesTableViewCell)
            
        }
        cell.replayBtnCallback = {[weak self](clickCell) -> () in
            self?.replayBtnClicked(cell: clickCell as! HSMessagesTableViewCell)
        }

        return cell
    }
    //即将显示某行时调用
    
        override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
            let messageVM = messageListVM.messages[indexPath.row]
    
            return messageVM.cellHeight
        }

}

// MARK: - 点赞回复相关功能
extension HSMessagesTableViewController {
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        let keyWindow = UIApplication.shared.keyWindow
        keyWindow?.endEditing(true)
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        //注册监听键盘弹出的通知
        NotificationCenter.default.addObserver(self, selector: #selector(notificationWithKeyboard(notify:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }
    
    
    //输入框视图
    func inputTextView() {
        inputToolBarV = UIView(frame: CGRect(x: 0, y: screenH, width: screenW, height: 44))
        inputToolBarV.backgroundColor = #colorLiteral(red: 0.9411764706, green: 0.9411764706, blue: 0.9411764706, alpha: 1)
        
        
        inputTextF = UITextField(frame: CGRect(x: 5, y: 2, width: screenW - 68, height: 40))
        inputTextF.placeholder = "评论要有价值"
        inputTextF.borderStyle = .roundedRect
        inputTextF.clearButtonMode = .always
        inputTextF.font = UIFont.systemFont(ofSize: 15)
        inputTextF.textColor = #colorLiteral(red: 0.2980392157, green: 0.2980392157, blue: 0.2980392157, alpha: 1)
        inputToolBarV.addSubview(inputTextF)
        
        let suerBtn = UIButton(frame: CGRect(x: screenW - 55, y: 0, width: 50, height: 44))
        suerBtn.setTitle("确定", for: .normal)
        suerBtn.setTitleColor(#colorLiteral(red: 0.3647058904, green: 0.06666667014, blue: 0.9686274529, alpha: 1), for: .normal)
        //按钮的监听回调
        suerBtn.addTarget(self, action: #selector(sureBtnClicked), for: .touchUpInside)
        
        inputToolBarV.addSubview(suerBtn)
        
        let kWindow = UIApplication.shared.keyWindow
        kWindow?.addSubview(inputToolBarV)
    }
    
    func likeBtnClicked(cell:HSMessagesTableViewCell) {
        currentCell = cell
        
        let url = "ZH-schoolname-S-submitJXLike"
        let key = userInfo["key"] ?? 0
        let messageVM = currentCell.messageVM
        let id = messageVM?.message.not_id ?? 0
        let parm = ["key":key,"id":id,"user_type":2]
        HSNetWorkTools.shared.downloadData(url: url, parameters: parm) { [weak self](data, err) in
            guard let data = data as? NSDictionary else {
                HSAlertView.bottomAlertView("网络连接异常")
                return
            }
            print(data["data"]!)
            switch data["result"] as! Int {
            case 0:
                
                let message = messageVM?.message
                let arr = data["data"] as! [[String:Any]]
                let dict = arr.last
                
                message?.likelist = dict?["likelist"] as! String?
                message?.likenum = dict?["likenum"] as! Int
                messageVM?.message = message!
                
                self?.tableView.reloadData()
                
            case 1:
                HSAlertView.bottomAlertView("你已经点赞过了")
            default:
                break
            }
            
        }
    }
    @objc fileprivate func sureBtnClicked() {
        inputTextF.resignFirstResponder()
        
        let inputText = inputTextF.text!
        
        inputTextF.text = ""
        
        if inputText == "" {
           
            return
        }
        isMove = false
        let url = "ZH-schoolname-S-submitJXReplay"
        
        let key = userInfo["key"] ?? 0
        let messageVM = currentCell.messageVM
        let id = messageVM?.message.not_id ?? 0
        
        //回复人类型
        /*
         
         不能硬敲！！！
         不能硬敲！！！
         不能硬敲！！！
         重要的事情说三次！
         
         */
        let parm = ["key":key,"id":id,"content":inputText,"user_type":2]
        
        HSNetWorkTools.shared.downloadData(url: url, parameters: parm) {[weak self] (data, err) in
           
           //获得回复列表字典数组
            guard let data = data as? NSDictionary else {
                HSAlertView.bottomAlertView("网络连接异常")
                return
            }
            switch data["result"] as! Int {
            case 0:
                let listArray = data["data"] as! [[String:Any]]
                var modelArray = [HSReplaylistModel]()
                for dict in listArray {
                    let listModel = HSReplaylistModel(dict: dict)
                    modelArray.append(listModel)
                }
                let message = messageVM?.message
                
                message?.replaylist = modelArray
                messageVM?.message = message!
                
                self?.tableView.reloadData()
              //  获得当前cell 的indexPath
//                guard let indexPath = self?.tableView.indexPath(for: (self?.currentCell)!) else {
//                    return
//                }
//                self?.tableView.reloadRows(at: [indexPath], with: .automatic)
                
            case 1:
                HSAlertView.bottomAlertView("发送失败")
            default:
                break
            }
 
        }
       
    }
    
    func replayBtnClicked(cell:HSMessagesTableViewCell) {
        
        currentCell = cell
        
        //设置输入框为第一响应者
        if isKeyboardShow {
            inputTextF.resignFirstResponder()
        } else {
            inputTextF.becomeFirstResponder()
        }
        
    }
    //键盘通知的回调
    func notificationWithKeyboard(notify:Notification) {
        
        if isMove {
            tableView.setContentOffset(CGPoint(x: 0, y: currentOffsetY), animated: true)
        }
        
        isMove = false
        
        let keyBoardRect = notify.userInfo?["UIKeyboardFrameEndUserInfoKey"] as? NSValue
        
        let keyBoardY = keyBoardRect?.cgRectValue.minY ?? 0
        
        isKeyboardShow = keyBoardY < screenH
        
        //计算工具栏的y值
        let toolBarY = isKeyboardShow ? (keyBoardY - inputToolBarV.frame.size.height) : (keyBoardY + inputToolBarV.frame.size.height)
        inputToolBarV.frame.origin.y = toolBarY
        
        //适配表格视图高度
        let keyWindow = UIApplication.shared.keyWindow
        let cellFrame = keyWindow?.convert(currentCell.frame, from: tableView)
        //获得cell的底部y值
        let cellMaxY = cellFrame?.maxY ?? 0
        let offsetY = cellMaxY - toolBarY
        
        if offsetY > 0 {
            currentOffsetY = tableView.contentOffset.y
            isMove = true
            tableView.setContentOffset(CGPoint(x: 0, y: offsetY + currentOffsetY), animated: true)
        }
    }
    //滚动退出
    override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        inputTextF.resignFirstResponder()
    }
    
}
